import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';
// 获取当前文件的路径
const __filename = fileURLToPath(import.meta.url);
// 获取当前文件的目录
const __dirname = path.dirname(__filename);
const ikUiDir = path.join(__dirname, 'ikicons');
const savepath = path.join(__dirname, 'ikicons', 'package.json');
const faterpath = path.join(__dirname, 'package.json');
const npmc = path.join(__dirname, 'ikicons', '.npmrc');
const npmctext = path.join(__dirname, '.npmrcs');
const clonePath = path.join(__dirname, 'public','clonePackage.json');
execSync('cd ' + ikUiDir + ' && npm init -y', { stdio: 'inherit' });
async function buildAndUpdatePackage() {
  try {
    // 读取当前的 package.json 文件
    const packageJson = JSON.parse(await fs.readFile(faterpath, 'utf-8'));

    // 执行 Vite 构建
    execSync('vite build', { stdio: 'inherit' });
    execSync('cd ' + ikUiDir + ' && npm init -y', { stdio: 'inherit' });
    // 更新 package.json 的内容
    const nowpackageJson = JSON.parse(await fs.readFile(savepath, 'utf-8'));
    const updatedPackageJson = JSON.stringify({
      ...nowpackageJson,
      name: packageJson.name,
      version: packageJson.version,
      private: false,
      "keywords": ["ikicons"],
      "author": "ljh",
      "license": "MIT",
    }, null, 2);

    // 写回 package.json 文件
    await fs.writeFile(savepath, updatedPackageJson);
    const nownpmc = await fs.readFile(npmctext, 'utf-8')
    await fs.writeFile(npmc, nownpmc);
    console.log('package.json has been updated.');
  } catch (error) {
    console.error('An error occurred:', error);
  }
}
buildAndUpdatePackage();